
const UserService = require('../services/User');
const ResolveRecordService = require('../services/ResolveRecord');
const ResolveListService = require('../services/ResolveList');
const LoginInfoService = require('../services/LoginInfo');
const RecommendListService = require('../services/RecommendList');
const DataTableService = require('../services/DataTable');
const ProblemService = require('../services/Problem');
const ProblemTypeService = require('../services/ProblemType');
const RecommendWeightBaseService = require('../services/RecommendWeightBase');
const RecommendWeightAdvanceService = require('../services/RecommendWeightAdvance');


const tools = {
  //处理含题目pid的数组
  async excludeResolveProblemPid(problemArr, resolveArr) {
    resolveArr.forEach((item, idx) => {
      var itemStr = item + '';
      let index = problemArr.indexOf(itemStr); //完全匹配
      if (index != -1) {
        if(index == problemArr.length - 1) {
          problemArr.pop();
        }else {
          problemArr[index] = problemArr.pop(); //这里要判断是否是最后一位，不然js解析会有歧义
        }
      }
    });
    return problemArr;
  },

  async excludeResolveProblemRes(problemsRes, resolveArr) {
    resolveArr.forEach((item, idx) => {
      let index = -1;
      for (var i = 0; i < problemsRes.length; i++) {
        let pid = problemsRes[i].get('pid');
        if (pid == item) {
          index = i;
          break;
        }
      }
      if (index != -1) {
        if(index == problemsRes.length - 1) { 
          problemsRes.pop();
        }else {
          problemsRes[index] = problemsRes.pop();
        }
      }
    })
    return problemsRes;
  }
}

module.exports = async (ctx) => {
  //错题权重与推荐数量
  let errLevelFirstNum = 1;
  let errLevelSecondNum = 2;

  //查询数量，isBasic
  const amount = +ctx.userModel.get('recom_amount');
  const isBasic = ctx.userModel.get('isBasic');
  const userId = ctx.userModel.get('id');

  //错题保存
  const errListArr = [];

  //查历史推荐表
  const recomList = await RecommendListService.findRecomListById(userId); //无结果为null
  let newRecomList = [];

  //用户做过的题目 所有题目
  const resolveListRes = await ResolveListService.findResolveListById(userId);
  const resolveList = resolveListRes.get('resolve_list');
  let resolveArr = resolveList.split(',');

  const allData = await DataTableService.getData();
  const allProblemPid = allData.get('all_problem_pid');

  //生成未做过的题
  let problemArr = allProblemPid.split(','); //所有题目 -> 未做的题目
  problemArr = await tools.excludeResolveProblemPid(problemArr, resolveArr);

  //初次生成推荐列表
  if (!recomList) {
    //生成
    for (var i = 0; i < amount; i++) {
      let index = Math.floor(Math.random() * problemArr.length);
      newRecomList.push(problemArr[index]);
      if (index == problemArr.length - 1) {
        problemArr.pop();
      } else {
        problemArr[index] = problemArr.pop();
      }
    }
    //结束
  } else {

    //找上次推荐的错题结果 放入error_problem_list
    const preRecomArr = recomList.get('recom_list').split(',');
    //上次推荐题的做题结果
    const preProblemResult = await ResolveRecordService.findRecordByIdGroup(preRecomArr, userId);
    await preProblemResult.forEach(item => {
      if (item.submit_result == 0) {
        errListArr.push(item.pid);
      }
    })

    //查权重
    if (isBasic == 1) {
      let recom_weight_base = await RecommendWeightBaseService.findRecomWeightBaseById(userId);
      let dataTableRes = await DataTableService.getData();

      let type_id_list = [],
        weight_list_arr = [],
        all_basic_type_arr = [];

      //查所有基础类型
      all_basic_type_arr = dataTableRes.get('all_basic_type').split(',');

      //权重检查赋值
      if (!recom_weight_base) {
        //无权重则创建
        for (var i = 0; i < all_basic_type_arr.length; i++) {
          weight_list_arr.push(10);
        }

        await RecommendWeightBaseService.addRecomWeightBase({
          userId,
          type_id_list: all_basic_type_arr.join(','),
          weight_list: weight_list_arr.join(',')
        })

      } else {
        //有权重则赋值
        type_id_list = recom_weight_base.get('type_id_list').split(',');
        weight_list_arr = recom_weight_base.get('weight_list').split(',');

        if (type_id_list.length != all_basic_type_arr.length) {
          //type数量出现更改
          for (var i = type_id_list.length; i <= all_basic_type_arr.length; i++) {
            weight_list_arr.push(10);
          }

          await RecommendWeightBaseService.addRecomWeightBase({
            userId,
            type_id_list: all_basic_type_arr.join(','),
            weight_list: weight_list_arr.join(',')
          })

          recom_weight_base = await RecommendWeightBaseService.findRecomWeightBaseById(userId);
          type_id_list = recom_weight_base.get('type_id_list').split(',');
          weight_list_arr = recom_weight_base.get('weight_list').split(',');
        }
      }

      if (preProblemResult) {
        //根据错题对权重加工
        preProblemResult.forEach((item, idx) => {
          //错题
          if (item.submit_result == 0) {
            let type_id = item.problemTypeId;
            let index = type_id_list.indexOf(type_id + '');
            let weightVal = weight_list_arr[index];
            if (weightVal >= 10 && weightVal < 15) {
              weight_list_arr[index] = +weight_list_arr[index] + 1;
            }
          }
          //Access
          else if (item.submit_result == 1) {
            let type_id = item.problemTypeId;
            let index = type_id_list.indexOf(type_id + '');
            let weightVal = weight_list_arr[index];
            if (weightVal > 10 && weightVal <= 15) {
              weight_list_arr[index] = +weight_list_arr[index] - 1;
            }
          }
        })
      }

      //选出权重大于10的类型id
      const firstTypeIdArr = [],
        firstWeightArr = [];

      for (var i = 0; i < weight_list_arr.length; i++) {
        if (weight_list_arr[i] > 10) {
          firstWeightArr.push(weight_list_arr[i]);
          firstTypeIdArr.push(type_id_list[i]);
        }
      }

      //组合推荐题目
      for (var i = 0; i < firstWeightArr.length; i++) {
        //选出该类型的题目
        let theTypeProblem = await ProblemService.findProblemByTypeId(firstTypeIdArr[i]);
        //去掉做过的题
        theTypeProblem = await tools.excludeResolveProblemRes(theTypeProblem, resolveArr);

        //判断该类型题数量大于0
        if (theTypeProblem.length == 0) {
          continue;
        }

        if (firstWeightArr[i] > 13) {

          if (theTypeProblem.length >= 2) {
            for (var i = 0; i < errLevelSecondNum; i++) {
              let index = Math.floor(Math.random() * theTypeProblem.length);
              newRecomList.push(theTypeProblem[index].get('pid'));
              if (index == theTypeProblem.length - 1) {
                theTypeProblem.pop();
              } else {
                theTypeProblem[index] = theTypeProblem.pop();
              }
            }
          } else {
            let index = Math.floor(Math.random() * theTypeProblem.length);
            newRecomList.push(theTypeProblem[index].get('pid'));
          }

        } else if (firstWeightArr[i] > 10) {

          if (theTypeProblem.length >= 2) {
            for (var i = 0; i < errLevelFirstNum; i++) {
              let index = Math.floor(Math.random() * theTypeProblem.length);
              newRecomList.push(theTypeProblem[index].get('pid'));
              if (index == theTypeProblem.length - 1) {
                theTypeProblem.pop();
              } else {
                theTypeProblem[index] = theTypeProblem.pop();
              }
            }
          } else {
            let index = Math.floor(Math.random() * theTypeProblem.length);
            newRecomList.push(theTypeProblem[index].get('pid'));
          }
        }
      }

      //在未做过的题目中排除已推荐题目
      // problemArr pid数组
      // newRecomList pid数组
      problemArr = await tools.excludeResolveProblemPid(problemArr, newRecomList);

      //组合剩下的题目 补全
      //problemArr 未做的题目
      for (var i = newRecomList.length; i < amount; i++) {
        let index = Math.floor(Math.random() * problemArr.length);
        newRecomList.push(problemArr[index]);
        if (index == problemArr.length - 1) {
          problemArr.pop();
        } else {
          problemArr[index] = problemArr.pop();
        }
      }
    }
  }

  //保存错题
  let errListStr = '';
  if (errListArr.length > 0) {
    errListStr = errListArr.join(',');
  }

  // //保存列表
  // const RecomListRes = await RecommendListService.addRecomList({
  //   userId,
  //   recom_list: newRecomList.join(','),
  //   recom_time: new Date().toString(),
  //   error_problem_list: errListStr
  // })

  //组合推荐题目信息
  const recomProblemList = await ProblemService.findProblemByIdGroup(newRecomList);
  const problem_type = await ProblemTypeService.getAllProblemType();

  // 添加type字段 problemTypeId ->  type
  const typeObj = {};

  problem_type.forEach((item, index) => {
    typeObj[item.id] = item.type_title;
  });

  recomProblemList.map((item, index) => {
    item.type = typeObj[item.problemTypeId];
    return item;
  })

  return recomProblemList;
}